import 'dart:async';

import 'package:dolqun_movies/Entities/UserInformationResult.dart';
import 'package:dolqun_movies/StateManagement/ModelProvider.dart';
import 'package:dolqun_movies/UI/Pages/Models/WechatApiModel.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:uuid/uuid.dart';
import 'package:wechat_kit/wechat_kit.dart';

class EnsureHasSignIn extends StatelessWidget {
  Widget Function(WechatApiModel) builder;

  EnsureHasSignIn({this.builder});
  @override
  Widget build(BuildContext context) {
    return ModelDescendant<WechatApiModel>(
      onChanged: (context, child, wechatModel) {
        var hasSignIn = wechatModel.userInfo != null;
        return hasSignIn ? builder(wechatModel) : EnsureHasSignIn._buildShouldSignInDialog(context, () => wechatModel.signInWithWechat());
      },
    );
  }
  static _buildShouldSignInDialog(BuildContext context, void action()) {
    return CupertinoAlertDialog(
      title: Text("بۇ يەردە بىر مەسىلە مەۋجۇت"),
      content: Text("داۋاملاشتۇرۇش ئۈچۈن ئاۋال ھىساباتىڭىز بىلەن كىرىڭ، ھازىر كىرەمسىز؟"),
      actions: <Widget>[
        CupertinoButton(
          child: Text("ھەئە"),
          onPressed: (){
            action();
          },
        ),
        CupertinoButton(
          child: Text("بولدىلا"),
          onPressed: (){
            Navigator.of(context).pop();
          },
        ),
      ],
    );
  }
  static runWhenSignIn(BuildContext context, void action()) {
    var model = ModelContainer.of<WechatApiModel>(context).model;
    var hasSignIn = model.userInfo != null;
    if (!hasSignIn) {
      var uuid = Uuid().v4();
      StreamSubscription<UserInformationResult> subscriber;
      subscriber = model.onUserSignIn.listen((event) {
        subscriber.cancel();
        action();
      });
      showDialog(context: context, barrierDismissible: false, child: _buildShouldSignInDialog(context, () async {
        await model.signInWithWechat(state: uuid);
        Navigator.of(context).pop();
      }));
      return;
    }
    action();
  }
}